package com.zhang.zhangapp.bean.user;

import android.database.Cursor;

import com.zhang.zhangapp.application.MApplication;

import org.xutils.x;

import java.util.List;

/**
 * Created by Administrator on 2018/4/18.
 */

public class SearchHistoryDao {
    static SearchHistoryDao instance;

    public static SearchHistoryDao getInstance() {
        if (instance == null)
            instance = new SearchHistoryDao();
        return instance;
    }

    public void save(String keyword) {
        if (keyword == null || keyword.equals(""))
            return;
        try {
            SearchHistory searchHistory = new SearchHistory(keyword);
            Cursor cursor = x.getDb(MApplication.getInstance().getDaoConfig()).execQuery("select * from z_search_history where keyword = \'" + keyword + "\'");
            if (cursor != null) {
                while (cursor.moveToNext()) {
                    int id = cursor.getInt(cursor.getColumnIndex("id"));
                    x.getDb(MApplication.getInstance().getDaoConfig()).deleteById(SearchHistory.class, id);
                }
            }
            // x.getDb(MApplication.getInstance().getDaoConfig()).execQuery("delete form z_search_history where keyword = \'"+keyword +"\'");
            x.getDb(MApplication.getInstance().getDaoConfig()).saveOrUpdate(searchHistory);
            x.getDb(MApplication.getInstance().getDaoConfig()).close();
        } catch (Exception e) {
        }
    }

    public String[] getAllHistory() {
        String[] arr = null;
        try {
            List<SearchHistory> list = x.getDb(MApplication.getInstance().getDaoConfig()).findAll(SearchHistory.class);
            if (list != null) {
                arr = new String[list.size() > 10 ? 10 : list.size()];
                int i = 0;
                for (SearchHistory keyword : list) {
                    if (i > (arr.length - 1))
                        break;
                    arr[i] = keyword.getKeyword();
                    i++;
                }
            }
            x.getDb(MApplication.getInstance().getDaoConfig()).close();
        } catch (Exception e) {
        }
        return arr;
    }

    public void deleteAll() {
        try {
            x.getDb(MApplication.getInstance().getDaoConfig()).delete(SearchHistory.class);
        } catch (Exception e) {
        }
    }
}
